import Hapi  from '@hapi/hapi'
import jwt from 'hapi-auth-jwt2'
import { Database,systemConfig } from "./config";
import path from "path";
import fs from "fs";
import vision from '@hapi/vision'
import handlebars from 'handlebars'
import Inert from '@hapi/inert'


const validate = async function (decoded, request, h) {
    console.log(decoded)
    return { isValid: true }
}
console.log(path.join(__dirname, 'public'));
const init = async () => {
    const server = Hapi.server({
        port: systemConfig.port,
        host: '0.0.0.0',
        routes: {
            cors: {
                origin: ['*']
            },
            files: {
                relativeTo: path.join(__dirname, 'public')
            }
        }
    });

    // mongo connect
    await Database.connect()

    await server.register(Inert)
    server.route({
        method: 'GET',
        path: '/{param*}',
        config: {auth: false},
        handler: {
            directory: {
                path: '.',
                redirectToSlash: true,
                index: true,
            }
        }
    })

    // jwt plugin set
    await server.register(jwt)
    let pt = path.join(__dirname, '../jwtsign.key')
    let pk = fs.readFileSync(pt,'utf8');
    server.auth.strategy('jwt', 'jwt', {
        key: pk,
        validate
    })
    server.auth.default('jwt')

    // view engine set
    await server.register(vision)
    server.views({
        engines: {
            html: handlebars
        },
        relativeTo: __dirname,
        path: 'templates'
    })

    // route plugin set
    await server.register([
        { plugin: require('./routes/auth') },
        { plugin: require('./routes/video')}
    ])
    await server.start()
    console.log('Server running on %s', server.info.uri)
};


process.on('unhandledRejection', (err) => {
    console.error(err);
    process.exit(1);
});

init();
